﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EtlComm;
using System.Xml.Linq;
using System.Timers;
using System.Threading;
using System.IO;
using ETLHandler;
using EtlData.Services;

namespace TaskToLineUp
{
    public static class TaskQueuer
    {
        private static ILog log = LogFactory.CreateLog<ServiceBaseLog>();

        /// <summary>
        /// 加油站任务列表
        /// </summary>
        public static IList<StationObject> StationObjectList 
        { 
            get{return InitStationTask();} 
        }

        //private static System.Timers.Timer t = new System.Timers.Timer();
        //private static ElapsedEventHandler eeh = new ElapsedEventHandler(t_Elapsed);
        /// <summary>
        /// 初始加油站任务列表
        /// </summary>
        /// <returns>初始化的任务列表</returns>
        private static IList<StationObject> InitStationTask()
        {
            log.WriteLog(string.Format("{0}\t初始化任务...",DateTime.Now));
            XElement XEStation = null;
            XElement XETask = null;
            try
            {
                lock (LockObject.XmlFileLock)
                {
                    XEStation = XElement.Load(EtlGlobal.XmlStationFile);
                    XETask = XElement.Load(EtlGlobal.XmlTaskFile);
                }
            }
            catch (System.Exception ex)
            {
                log.WriteLog(ex.Message);
                return null;
            }
            
            var Tasklist = from a in XETask.Descendants("Task")
                           select a;

            var Stationlist = from a in XEStation.Descendants("Station")
                              select a;
            IStation ista = new StationService();
            var stations = ista.GetStations();
            //创建加油站任务列表
            var RetlstStationObject = (from a in Stationlist
                           join b in stations on a.Element("StationID").Value equals b.SYS_CODE
                           select new StationObject
                             {
                                 Station = new StationInfo
                                 {
                                     StationID = a.Element("StationID").Value,
                                     StationName = b.STATION_NAME,
                                     IsActive = a.Element("IsActive").Value == "1",
                                     InterBaseIP = string.Format(a.Element("InterBaseIP").Value,b.IP_ADD,b.FILE_ADD),
                                     MySQLIP = a.Element("MySQLIP").Value,
                                     DestIP = a.Element("DestIP").Value,
                                     Interval = uint.Parse(a.Element("Interval").Value)
                                 },
                                 StationTaskQueue = new TaskQueue(),
                                 TaskEvent = new AutoResetEvent(false)
                             }).ToList();
            //初始化任务
            foreach (var item in RetlstStationObject)
            {
                TaskObject taskObj = null;
                var taskinfo = (from a in Stationlist
                        where a.Element("StationID").Value == item.Station.StationID
                        select a.Descendants("TaskInfo")).FirstOrDefault();
                var y = from b in Tasklist
                        join tt in taskinfo on b.Element("TaskID").Value equals tt.Element("TaskID").Value
                        let pt = b.Element("HaveParams").Value == "1" ? (StepType)Enum.Parse(typeof(StepType),b.Element("Step").Attribute("StepType").Value.ToUpper()) : StepType.NONE
                        select new {
                            SrcDS = (DataSource)Enum.Parse(typeof(DataSource), b.Element("DataSource").Value),
                            SQLStatement = b.Element("SQLStatement").Value,
                            TaskID = int.Parse(b.Element("TaskID").Value),
                            TaskName = b.Element("TaskName").Value,
                            Action = (SQLAction)Enum.Parse(typeof(SQLAction), b.Element("Action").Value),
                            ParamsStart = tt.Element("StartTime").Value,
                            ParamsEnd = tt.Element("EndTime").Value,
                            HasParams = b.Element("HaveParams").Value == "1",
                            Step = int.Parse(b.Element("Step").Value),
                            ParamType = pt,
                            PrimaryKeys = b.Element("PrimaryKey").Value.Split('|')
                        };
                foreach (var d in y)
                {
                    string strip = "";
                    switch (d.SrcDS)
                    {
                        case DataSource.IB:
                            strip = item.Station.InterBaseIP;
                            break;
                        case DataSource.MYSQL:
                            strip = item.Station.MySQLIP;
                            break;
                        case DataSource.MSSQL:
                            strip = item.Station.DestIP;
                            break;
                    }
                    taskObj = new TaskObject
                    {
                        StationID = item.Station.StationID,
                        SrcIP = strip,
                        DstIP = item.Station.DestIP,
                        SQLStatement = d.SQLStatement,
                        Executions = 0,
                        TaskID = d.TaskID,
                        TaskName = d.TaskName,
                        Action = d.Action,
                        SrcDS = d.SrcDS,
                        DstDS = DataSource.MSSQL,
                        ParamsStart = d.ParamsStart,
                        ParamsEnd = d.ParamsEnd,
                        HasParams = d.HasParams,
                        Params = new string[]{d.SQLStatement},
                        Step = d.Step,
                        ParamType = d.ParamType,
                        PrimaryKeys = d.PrimaryKeys
                    };

                    item.StationTaskQueue.Push(taskObj);
                }
            }
            log.WriteLog(string.Format("{0}\t任务列表初始化成功.", DateTime.Now));
            return RetlstStationObject;
        }
    }
}
